package com.cimpm.networkDisk.utils;

import com.hby.common.annotation.Remind;
import com.hby.common.configs.entity.ConfigBean;
import com.hby.common.exceptions.AutoException;
import com.hby.common.exceptions.ExceptionEnum;
import org.apache.catalina.connector.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class NetworkDiskFileIOUtil {

    private static NetworkDiskFileIOUtil instance;

    //包含路径相关配置
    //该工具调用时只是用
    // instance.configBean.getNetworkDiskPath()
    // instance.configBean.getNetworkDiskUrl() 两个配置
    @Autowired
    private ConfigBean configBean;

    @PostConstruct
    public void init(){
        instance = this;
        instance.configBean = this.configBean;
    }

    public static String getUrl(){
        return instance.configBean.getNetworkDiskUrl();
    }

    public static String getStorePath(){
        return instance.configBean.getNetworkDiskPath();
    }

    //获取文件后缀 无后缀返回null
    public static String getFileExtension(String name){
        int extension = name.lastIndexOf(".");
        if (extension == -1) {
            return null;
        } else {
            return name.substring(name.lastIndexOf("."));
        }
    }

    //验证路径下文件是否重名，返回最终命名
    @Remind("path包含StorePath，业务中不再添加StorePath")
    public static String hasSameName(String path,String name){
        //验证文件是否存在
        File file = new File(path + name);
        if (file.exists()) {
            String extension = getFileExtension(name);
            String prefix = name;
            if (extension!=null)
                prefix = name.substring(0, name.lastIndexOf("."));
            Integer count = 1;
            boolean stat = true;
            while (stat){
                File fileExist = new File(path + prefix + "("+ count +")"+(extension==null?"":extension));
                if (fileExist.exists())
                    count++;
                else
                    stat =false;
            }
            return prefix+"("+ count +")"+(extension==null?"":extension);
        } else {
            return name;
        }
    }

    @Remind("path包含StorePath，业务中不再添加StorePath")
    public static String hasSameNameFolder(String path,String name){
        //验证文件是否存在
        File file = new File(path + name);
        if (file.exists()&&file.isDirectory()) {
            String prefix = name;
            Integer count = 1;
            boolean stat = true;
            while (stat){
                File fileExist = new File(path + prefix + "("+ count +")");
                if (fileExist.exists())
                    count++;
                else
                    stat =false;
            }
            return prefix+"("+ count +")";
        } else {
            return name;
        }
    }

    public static void renameFile(String path,String name,String newName) throws Exception{
        File file = new File(getStorePath()+path + name);
        if (file.exists()&&file.isFile()) {
            boolean result = file.renameTo(new File(getStorePath()+path + newName));
            if (result) return;
             else throw new Exception("文件重命名失败");
        }
        throw new AutoException(ExceptionEnum.NOT_EXIST,"文件不存在");
    }

    public static void renameFolder(String path,String name,String newName,boolean isMerge)throws Exception{
        File file = new File(getStorePath()+path + name);
        File fileDes = new File(getStorePath()+path + newName);
        if (fileDes.exists() && fileDes.isDirectory()) throw new Exception("文件夹重名");
        if (file.exists() && file.isDirectory()){
            boolean result = file.renameTo(fileDes);
            if (result) return;
            else throw new Exception("文件夹重命名失败");
        }
        throw new AutoException(ExceptionEnum.NOT_EXIST,"文件夹不存在");
    }

    //返回值包含两个key，folder 和 file；value为 List(string) (如果路径不存在返回null，目录无内容返回空)
    //不包含 .delete文件
    public static Map<String,Object> getFolderContains(String path){
        Map<String, Object> map = new HashMap<>();
        File folder = new File(getStorePath()+path);
        // 如果路径不存在返回null
        if (!folder.exists()) throw new AutoException(ExceptionEnum.NOT_EXIST,"文件夹不存在");
        File[] filesArr = folder.listFiles();
        List<String> files = new ArrayList<>();
        List<String> folders = new ArrayList<>();
        for (File file:filesArr){
            String fileExtension = getFileExtension(file.getName());
            if (fileExtension!=null && fileExtension.equals(".delete")) continue;
            if (file.isFile()) files.add(file.getName());
            else folders.add(file.getName());
        }
        map.put("files",files);
        map.put("folders",folders);
        return map;
    }

    public static void createFile(String path,String fileName) throws Throwable {
        File file = new File(getStorePath()+path + fileName);
        if (!file.exists()) {
            boolean result = file.createNewFile();
            if (!result) throw new Exception("文件创建失败");
        } else throw new Exception("文件存在重名");
    }

    public static void createFolder(String path,String folderName) throws Throwable{
        File dir = new File(getStorePath()+path + folderName);
        if (!dir.exists()) {
            boolean result = dir.mkdir();
            if (!result) throw new Exception("文件夹创建失败");
        } else throw new Exception("文件夹存在重名");
    }

    public static void deleteFile(String path,String name,String deleteName)throws Throwable{
        File file = new File(getStorePath()+path + name);
        if (file.exists()) {
            if (!file.isFile()) throw new AutoException(ExceptionEnum.NOT_EXIST,"非文件类型");
            String finalName = hasSameName(getStorePath()+path, deleteName);
            if (!finalName.equals(deleteName)) throw new Exception("文件删除失败:soft name error");
            boolean result = file.renameTo(new File(path + finalName));
            if (!result) throw new Exception("文件删除失败");
        } else throw new AutoException(ExceptionEnum.NOT_EXIST,"文件不存在");
    }


    public static void deleteFolder(String path,String name,String deleteName)throws Throwable{
        File file = new File(getStorePath()+path + name);
        if (file.exists()) {
            if (!file.isDirectory()) throw new AutoException(ExceptionEnum.NOT_EXIST,"非文件夹类型");
            String finalName = hasSameName(getStorePath()+path, deleteName);
            if (!finalName.equals(deleteName)) throw new Exception("文件夹删除失败:soft name error");
            boolean result = file.renameTo(new File(getStorePath()+path + finalName));
            if (!result) throw new Exception("文件夹删除失败");
        } else throw new AutoException(ExceptionEnum.NOT_EXIST,"文件夹不存在");
    }

}
